package com.baidu.exam.realm;

import com.baidu.exam.model.ExamUser;
import com.baidu.exam.service.IExamUserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Objects;

/**
 * <p>
 *
 * </p>
 *
 * @package: com.baidu.exam.realm
 * @description:
 * @className: ExamSysUserRealm
 * @author: @nncskj admin
 * @date: Created in 2022/5/31
 * @copyright: Copyright (c) 2022/5/31
 * @version: V1.0
 */
public class ExamSysUserRealm extends AuthorizingRealm {

    @Autowired
    private IExamUserService iExamUserService;

    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String username = (String) authenticationToken.getPrincipal();
        ExamUser examUser = iExamUserService.findExamUserByUsername(username);
        if (Objects.isNull(examUser)){
            return null;
        }
        return new SimpleAuthenticationInfo(examUser, examUser.getUpwd(), getName());
    }
}
